package com.siwei.mes.tgl.init;

import cn.hutool.core.date.StopWatch;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.siwei.mes.entity.tgl.TglItemorder;
import com.siwei.mes.tgl.queue.TglProcessorService;
import com.siwei.mes.tgl.service.SyncTglItemorderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * 项目启动初始化线程
 *
 * @Description: 项目启动初始化线程
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2024/2/3 11:48
 */
@Service
@Component
public class TglProcessorInitializing implements InitializingBean, DisposableBean {
    @Resource
    private TglProcessorService tglProcessorService;

    @Resource
    private SyncTglItemorderService syncTglItemorderService;

    private static final Logger log = LoggerFactory.getLogger("job");

    /**
     * 对应操作数据的队列
     */
    private BlockingQueue<Object> queue = null;
    /**
     * 只有一个线程的线程池
     */
    private ExecutorService workers;
    /**
     * 是否运行
     */
    private boolean runnable = true;
    /**
     * 休眠时间
     */
    private long sleepTime = 3000;

    public void process() {
        while (runnable) {
            try {
                if (queue.isEmpty()) {
                    this.sleep();
                } else {
                    Object entityObject = queue.take();
                    tglProcessorService.processRequest(entityObject);
//                    StopWatch stopWatch =new StopWatch();
//                    stopWatch.start();
//                    TglItemorder entity = new ObjectMapper().convertValue(entityObject, TglItemorder.class);
//                    syncTglItemorderService.genTglItemOrderTest(entity);
//                    this.sleep(500);
//                    stopWatch.stop();
//                    log.info("耗时：" + stopWatch.getTotalTimeMillis());
                }
            } catch (Exception e) {
                this.sleep();
            }
        }
        log.info("tgl任务处理器退出");
    }

    /**
     * 线程休眠
     */
    public void sleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(sleepTime);
        } catch (InterruptedException e) {
            log.warn("Thread interrupt exception", e);
        }
    }

    public void sleep(long time) {
        try {
            TimeUnit.MILLISECONDS.sleep(time);
        } catch (InterruptedException e) {
            log.warn("Thread interrupt exception", e);
        }
    }

    @Override
    public void destroy() throws Exception {
        this.runnable = false;
        if (this.workers != null) {
            workers.shutdown();
        }
    }

    @Override
    public void afterPropertiesSet() {
        this.workers = Executors.newSingleThreadExecutor();
        this.queue = new LinkedBlockingQueue<>();
        this.workers.submit(this::process);
        log.info("初始化TglProcessor 配置成功");
    }

    /**
     * 添加数据到队列
     *
     * @param request
     */
    public void submitRequest(Object request) {
        this.queue.offer(request);
    }

    /**
     * 获取队列长度
     *
     * @return
     */
    public Integer size() {
        return queue.size();
    }


}
